#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h> 
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MAXLINE 500
void main(int argc, char **argv)
{
	int listenfd,connfd,errcode;
	char buff[MAXLINE];
	socklen_t len;
	struct sockaddr_in servaddr,cliaddr;
	time_t ticks;
	
	if((listenfd=socket(AF_INET,SOCK_STREAM,0))<0)
	{
		printf("socket error\n");
		return;
	}
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_port=htons(13);
	servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
	
	errcode=0;
	if((errcode=bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)))<0)
	{
		printf("bind error\nerrcode=[%d]\nerrno=[%s]\n",errcode,strerror(errno));
		return;
	}
	if(listen(listenfd,1024)<0)
	{
		printf("listen error\n");
		return;
	}
	for(;;)
	{
		if((connfd=accept(listenfd,(struct sockaddr *)&cliaddr,&len))<0)
		{
			printf("accept error\n");
			return;
		}
		printf("connection from %s,port %d\n", inet_ntop(AF_INET,&(cliaddr.sin_addr),buff,sizeof(buff)),\
ntohs(cliaddr.sin_port));

		ticks=time(NULL);
		snprintf(buff,sizeof(buff),"%.24s\r\n",ctime(&ticks));
		if(write(connfd,buff,strlen(buff))<0)
		{
			printf("write error\n");
			return;
		}
		if(close(connfd)<0)
		{
			printf("close\n");
			return;
		}
	}

		
}



